package com.nefu.huiyi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nefu.huiyi.dto.Result;
import com.nefu.huiyi.entity.MedicalCompanyPolicy;
import com.nefu.huiyi.service.IMedicalCompanyPolicyService;
import com.nefu.huiyi.service.impl.MedicalCompanyPolicyServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/medical-policies")
public class MedicalCompanyPolicyController {

    @Autowired
    private IMedicalCompanyPolicyService policyService;

    @Autowired
    private MedicalCompanyPolicyServiceImpl policyServiceImpl;

    // 新增
    @PostMapping
    public Result<?> addPolicy(@RequestBody MedicalCompanyPolicy policy) {
        boolean success = policyService.save(policy);
        return success ? Result.success() : Result.error(500, "新增失败");
    }

    // 删除
    @DeleteMapping("/{id}")
    public Result<?> deletePolicy(@PathVariable Long id) {
        boolean success = policyService.removeById(id);
        return success ? Result.success() : Result.error(500, "删除失败");
    }

    // 修改
    @PutMapping
    public Result<?> updatePolicy(@RequestBody MedicalCompanyPolicy policy) {
        boolean success = policyService.updateById(policy);
        return success ? Result.success() : Result.error(500, "修改失败");
    }

    // 根据ID查询
    @GetMapping("/{id}")
    public Result<MedicalCompanyPolicy> getPolicyById(@PathVariable Long id) {
        MedicalCompanyPolicy policy = policyService.getById(id);
        return Result.success(policy);
    }

    // 根据公司ID分页查询政策
    @GetMapping("/page")
    public Result<?> getPolicyPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String policyName,
            @RequestParam(required = false) Long companyId) {

        Page<MedicalCompanyPolicy> page = new Page<>(pageNum, pageSize);
        QueryWrapper<MedicalCompanyPolicy> queryWrapper = new QueryWrapper<>();

        if (policyName != null && !policyName.isEmpty()) {
            queryWrapper.like("policy_name", policyName);
        }
        if (companyId != null) {
            queryWrapper.eq("company_id", companyId);
        }
        queryWrapper.orderByDesc("id");

        Page<MedicalCompanyPolicy> resultPage = policyServiceImpl.getPolicyPageWithDetails(page, queryWrapper);
        return Result.success(resultPage);
    }
}
